import './css/index.css';
let mask = document.querySelector('.mask');
let smallBox = document.querySelector('.smallBox');
let smallImg = smallBox.querySelector('img');
let bigBox = document.querySelector('.bigBox');
let bigImg = bigBox.querySelector('img');
let selectImg = document.querySelector('.selectImg');
let box = document.querySelector('.box');

// 遮罩层跟随鼠标移动
smallBox.addEventListener('mousemove', maskMove);

// 遮罩层移动函数
function maskMove(event) {
  // pageX、clientX
  // 遮罩层的移动值 - box偏移值 - (遮罩层 / 2)
  let moveX = event.pageX - box.offsetLeft - mask.offsetWidth / 2;
  let moveY = event.pageY - box.offsetTop - mask.offsetHeight / 2;

  // 最大移动距离
  let maxMoveX = smallBox.offsetWidth - mask.offsetWidth - smallBox.clientLeft;
  let maxMoveY = smallBox.offsetHeight - mask.offsetHeight - smallBox.clientTop;

  // 临界点判断
  // X轴
  moveX <= 0 && (moveX = 0);
  moveX >= maxMoveX && (moveX = maxMoveX);
  // Y轴
  moveY <= 0 && (moveY = 0);
  moveY >= maxMoveY && (moveY = maxMoveY);

  // 遮罩层
  mask.style.left = moveX + 'px';
  mask.style.top = moveY + 'px';

  // 计算大图移动的值
  // -moveX * 2  把2倍速和最终的值统一通过公式计算

  // 小最大移动距离100 / 大最大移动距离200
  // =
  // mask移动值 / 大图移动值(求此值)

  // 大图移动值(求此值) = 大最大移动距离200 / 小最大移动距离100 * mask移动值

  let bigImgMoveX =
    ((bigImg.offsetWidth - bigBox.offsetWidth) / maxMoveX) * moveX;
  let bigImgMoveY =
    ((bigImg.offsetHeight - bigBox.offsetHeight) / maxMoveY) * moveY;

  // 大图移动
  bigImg.style.transform = `translate(${-bigImgMoveX}px, ${-bigImgMoveY}px)`;
}
let selectImgList = selectImg.querySelectorAll('img');
let lastIndex = 0;
selectImg.addEventListener('mouseover', (event) => {
  if (event.target.localName == 'img') {
    let index = event.target.getAttribute('data-index');
    // 移除激活类
    selectImgList[lastIndex].classList.remove('active');
    // 添加激活类
    selectImgList[index].classList.add('active');
    // 修改图片地址
    smallImg.setAttribute('src', event.target.getAttribute('src'));
    bigImg.setAttribute('src', event.target.getAttribute('src'));
    // 保存上一次的记录值
    lastIndex = index;
  }
});
// 移开小盒子范围遮罩层和大图显示和隐藏
smallBox.addEventListener('mouseenter', () => {
  mask.style.display = 'block';
  bigBox.style.display = 'block';
});

smallBox.addEventListener('mouseleave', () => {
  mask.style.display = 'none';
  bigBox.style.display = 'none';
});
